﻿using LibraryManagement.Custom_Controls;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using LibraryManagement.Custom_Controls.Data_Grid_View;

namespace LibraryManagement.Inventory
{
    public partial class InvBookUpdation : libForm
    {
        private LibManagementEntities context;
        private BookDetail OBook;
        public InvBookUpdation()
        {
            InitializeComponent();
            context = new LibManagementEntities();
        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void InvBookUpdation_Load(object sender, EventArgs e)
        {
            dgvBooks.Columns.Add(new libDataGridViewColumnEdit());
            dgvBooks.Columns.Add(new libDataGridViewColumnDelete());
            SetDataGridView();
        }

        public void SetDataGridView()
        {
            context = new LibManagementEntities();
            //TODO: Create a new view to show books in the datagrid accordingly cuz isactive has been removed from BookDetails.S
            //var listBooks = context.BookDetails.Where(x => x.IsActive == true).ToList();
            var listBooks = context.BookDetails.ToList();
            dgvBooks.DataSource = listBooks;
        }

        private void dgvBooks_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex != -1)
            {
                decimal bookId = (decimal)dgvBooks.Rows[e.RowIndex].Cells["Id"].Value;
                if (e.ColumnIndex == dgvBooks.Columns["dgvcBtnEdit"].Index)
                {
                    InvBookAdd OInvBookAdd = new InvBookAdd(bookId, this, InvBookAdd.Redirection.Edit);
                    OInvBookAdd.MdiParent = this.MdiParent;
                    OInvBookAdd.Show();
                    this.Enabled = false;
                }
                else if (e.ColumnIndex == dgvBooks.Columns["dgvcBtnDelete"].Index)
                {
                    if (context.BookCopies.Where(x => x.BookId == bookId).ToList().Count > 0)
                    {
                        InvBookAdd OInvBookAdd = new InvBookAdd(bookId, this, InvBookAdd.Redirection.Delete);
                        OInvBookAdd.MdiParent = this.MdiParent;
                        OInvBookAdd.Show();
                        this.Enabled = false;
                    }
                    else
                    {
                        OBook = context.BookDetails.Single(x => x.Id == bookId);
                        context.BookDetails.Remove(OBook);
                        context.SaveChanges();
                    }
                }
            }
        }
    }
}
